﻿using System;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Tavis.Tools {
    public static class ContentExtensions {
        static readonly string DefaultXmlContentType = "application/xml";
        static readonly Encoding DefaultXmlEncoding = Encoding.UTF8;

        public static XElement ReadAsXElement(this HttpContent content) {
            return XElement.Load(new XmlTextReader(content.ReadAsStreamAsync().Result));
        }


        public static Image ReadAsImage(this HttpContent content) {
            if (content == null) return null;
            return Image.FromStream(content.ReadAsStreamAsync().Result);
        }


        public static HttpContent Create(Action<XmlWriter> writeTo, Encoding encoding, string contentType) {
            if (encoding == null) {
                throw new ArgumentNullException("encoding");
            }
            Action<Stream> streamWriter = (stream) => {
                using (var w = new XmlTextWriter(stream, encoding)) {
                    writeTo(w);
                    w.Flush();
                }
            };

            return Create(streamWriter, contentType);
        }
        
        public static HttpContent Create(XElement element) {
            return Create(element, DefaultXmlEncoding, DefaultXmlContentType);
        }
        public static HttpContent Create(XElement element, Encoding encoding, string contentType) {
            return Create(element.WriteTo, encoding, contentType);
        }


        public static ExceptionDetails ReadAsExceptionDetails(this HttpContent content) {
            if (content == null) return null;
            return content.ReadAsExceptionDetails();
        }

        public static HttpContent Create(Action<Stream> action, string contentType) {
            var memoryStream = new MemoryStream();
            action(memoryStream);
            var streamContent = new StreamContent(memoryStream);
            streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            return streamContent;
        }
    
    }
}
